package cn.bjc.product.service.impl;

import cn.bjc.basic.exception.BusinessException;
import cn.bjc.basic.service.IBaiduAiAuditService;
import cn.bjc.basic.service.impl.BaseServiceImpl;

import cn.bjc.product.domain.Product;
import cn.bjc.product.mapper.ProductDetailMapper;
import cn.bjc.product.mapper.ProductMapper;
import cn.bjc.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {
    
    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    
    //上架
    @Override
    public void onSale(List<Long> ids) {
        /**
         * 思路:
         *  1.审核
         *  1.改状态   sql中:state=1
         *  2.写入上架时间:创建一个当前时间.数据库写入
         *  传参方式:1.对象,2.map,3.直接写两个参数
         */
        //审核,通过则上架,没过则自定义异常
        
        //
        Date date = new Date();
        productMapper.onSale(ids,date);

    }

    //下架
    @Override
    public void offSale(List<Long> ids) {
        /**
         * 思路:
         *  1.改状态   sql中:state=0
         *  2.写入下架时间:创建一个当前时间.数据库写入
         *  传参方式:1.对象,2.map,3.直接写两个参数
         */
        Date date = new Date();
        productMapper.offSale(ids,date);
    }

    //删除
    @Override
    public void remove(Long id) {
        //删除产品表
        super.remove(id);
        //删除产品明细表
        productDetailMapper.removeByProductId(id);
    }

    @Override
    public void update(Product product) {
        audit(product);
        
        //更新product表
        productMapper.update(product);

        //更新detail表
        productDetailMapper.update(product.getProductDetail());

    }

    //添加
    @Override
    public void save(Product product) {
        audit(product);
        
        //写入product表
        productMapper.save(product);
        
        //获取product自增长主键
        product.getProductDetail().setProduct_id(product.getId());
        
        //写入detail表
        productDetailMapper.save(product.getProductDetail());
        
    }



    //百度自动审核
    private void audit(Product product){
        //文字审核
        Boolean textBoolean = baiduAiAuditService.textAudit(product.getName());
        if(!textBoolean){
            throw new BusinessException("数据不合法,请重新录入");
        }
        
        //图片审核
        String resources = product.getResources();
        String[] imgs = resources.split(",");
        
        for (String img : imgs) {
            Boolean imgBoolean = baiduAiAuditService.imageAudit("http://123.207.27.208"+img);
            if(!imgBoolean){
                throw new BusinessException("图片内容不合法,审核未通过");
            }
        }

    }
    
    
    
    
}
